const axios = require("axios");
const cheerio = require("cheerio");

async function getMoviesHTML() {
  const resp = await axios.get("https://movie.douban.com/chart");
  return resp.data;
}

async function getMoviesData() {
  const html = await getMoviesHTML();
  const $ = cheerio.load(html);
  const trs = $("tr.item");
  const movies = [];
  for (let i = 0; i < trs.length; i++) {
    const tr = trs[i];
    const m = getMovie($(tr));
    movies.push(m);
  }

  return movies;
}

function getMovie(tr) {
  const name = tr.find("div.pl2 a").text().replace(/\s/g, "").split("/")[0];

  const imgSrc = tr.find("a.nbg img").attr("src");

  const detail = tr.find("div.pl2 p.pl").text();
  return {
    name,
    imgSrc,
    detail,
  };
}

module.exports = getMoviesData;
